#include "lyrics_interface.h"
#include "ui_lyrics_interface.h"
#include <QScrollBar>
#include <QDebug>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QRegularExpressionMatchIterator>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QDialog>
#include <QListWidget>
#include <QMessageBox>

Lyrics_interface::Lyrics_interface(QWidget *parent) :
    QWidget(parent),
    // -------------------------- 按 private 成员声明顺序初始化 --------------------------
    ui(new Ui::Lyrics_interface),          // 1. UI 指针（最先初始化）
    mediaPlayer(nullptr),                  // 2. 媒体播放器
    lyricsTimer(nullptr),                  // 3. 歌词定时器（体内 new，此处设为 nullptr）
    progressTimer(nullptr),                // 4. 进度定时器（同上）
    lastLyricIndex(-1),                    // 5. 上次歌词索引
    isSliderPressed(false),                // 6. 进度条按压标记
    lyrics(QList<LyricLine>()),            // 7. 歌词列表（默认初始化）
    playlistDialog(nullptr),               // 8. 歌单对话框
    playlistListWidget(nullptr),           // 9. 歌单列表
    isPlaying(false),                      // 10. 播放状态
    currentVolume(50)                      // 11. 当前音量（最后初始化，匹配声明顺序）
{
    ui->setupUi(this);
    // 初始化定时器
    lyricsTimer = new QTimer(this);
    lyricsTimer->setInterval(200); // 每100毫秒更新一次

    progressTimer = new QTimer(this);
    progressTimer->setInterval(100); // 每100毫秒更新一次进度

    // 连接歌词界面的返回信号
        connect(ui->pushButton_7, &QPushButton::clicked, this, &Lyrics_interface::onBackButtonClicked);
        connect(lyricsTimer, &QTimer::timeout, this, &Lyrics_interface::updateLyricsDisplay);
        connect(progressTimer, &QTimer::timeout, this, &Lyrics_interface::updateProgress);
    // 连接进度条信号
        connect(ui->horizontalSlider, &QSlider::sliderMoved, this, &Lyrics_interface::onSliderMoved);
        connect(ui->horizontalSlider, &QSlider::sliderReleased, this, &Lyrics_interface::onSliderReleased);
    // 连接添加歌曲到歌单按钮
        connect(ui->pushButton_8, &QPushButton::clicked, this, &Lyrics_interface::onAddToPlaylistClicked);
    // 连接暂停/继续按钮
        connect(ui->pushButton, &QPushButton::clicked, this, &Lyrics_interface::onPlayPauseButtonClicked);
    // 连接新添加的按钮信号
            connect(ui->pushButton_2, &QPushButton::clicked, this, &Lyrics_interface::onRestartButtonClicked);     // 重新播放
            connect(ui->pushButton_3, &QPushButton::clicked, this, &Lyrics_interface::onPreviousButtonClicked);    // 上一首
            connect(ui->pushButton_4, &QPushButton::clicked, this, &Lyrics_interface::onNextButtonClicked);        // 下一首
            connect(ui->pushButton_5, &QPushButton::clicked, this, &Lyrics_interface::onVolumeAddButtonClicked);   // 音量+5%
            connect(ui->pushButton_6, &QPushButton::clicked, this, &Lyrics_interface::onVolumeSubButtonClicked);   // 音量-5%
            connect(ui->verticalSlider, &QSlider::valueChanged, this, &Lyrics_interface::onVolumeSliderMoved);     // 音量滑块

    // 设置文本浏览器属性
    ui->textBrowser->setAlignment(Qt::AlignCenter);
    ui->textBrowser->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->textBrowser->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    // 初始化时间显示
        ui->label->setText("00:00");
        ui->label_2->setText("00:00");

        // 设置进度条范围
        ui->horizontalSlider->setRange(0, 0);

        // 初始化音量控制
        ui->verticalSlider->setRange(0, 100);
        ui->verticalSlider->setValue(currentVolume);
        updateVolumeDisplay();

        // 设置按钮图标
        setupButtonIcons();

        // 初始化播放/暂停按钮
        updatePlayPauseButton();
}


// 显示歌单选择对话框
void Lyrics_interface::showPlaylistSelectionDialog()
{
    // 如果对话框已存在，先删除
    if (playlistDialog) {
        delete playlistDialog;
        playlistDialog = nullptr;
    }

    // 创建模态对话框
    playlistDialog = new QDialog(this);
    playlistDialog->setWindowTitle("选择歌单");
    playlistDialog->setFixedSize(400, 300);
    playlistDialog->setModal(true);

    // 创建布局
    QVBoxLayout *mainLayout = new QVBoxLayout(playlistDialog);

    // 添加提示标签
    QLabel *titleLabel = new QLabel("请选择要添加歌曲的歌单：", playlistDialog);
    mainLayout->addWidget(titleLabel);

    // 创建歌单列表
    playlistListWidget = new QListWidget(playlistDialog);
    mainLayout->addWidget(playlistListWidget);

    // 添加按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *confirmButton = new QPushButton("确认添加", playlistDialog);
    QPushButton *cancelButton = new QPushButton("取消", playlistDialog);

    buttonLayout->addWidget(confirmButton);
    buttonLayout->addWidget(cancelButton);
    mainLayout->addLayout(buttonLayout);

    // 连接按钮信号 - 修复：使用 lambda 表达式确保正确关闭
    connect(confirmButton, &QPushButton::clicked, this, [this]() {
        onPlaylistSelected();
    });

    connect(cancelButton, &QPushButton::clicked, playlistDialog, [this]() {
        playlistDialog->reject();
    });

    // 设置歌单列表
    QStringList examplePlaylists = {"我的收藏", "最近播放", "流行音乐", "经典老歌"};
    playlistListWidget->addItems(examplePlaylists);

    // 显示对话框
    playlistDialog->exec();
}

// 歌单选择确认 - 修复关闭逻辑
void Lyrics_interface::onPlaylistSelected()
{
    QListWidgetItem *currentItem = playlistListWidget->currentItem();
    if (!currentItem) {
        QMessageBox::warning(playlistDialog, "提示", "请选择一个歌单！");
        return;
    }

    QString playlistName = currentItem->text();

    // 先关闭对话框
    if (playlistDialog) {
        playlistDialog->accept();
        playlistDialog = nullptr; // 设置为nullptr避免重复删除
    }

    // 发射信号通知主界面添加歌曲到指定歌单
    emit addSongToPlaylistRequested(playlistName);

}

Lyrics_interface::~Lyrics_interface()
{
    delete ui;
}


// 添加"暂停/继续"按钮点击处理函数
void Lyrics_interface::onPlayPauseButtonClicked()
{
    if (!mediaPlayer) {
        return;
    }

    if (mediaPlayer->state() == QMediaPlayer::PlayingState) {
        // 如果正在播放，则暂停
        mediaPlayer->pause();
        isPlaying = false;
        qDebug() << "Music paused from lyrics interface";
    } else {
        // 如果暂停或停止，则播放
        mediaPlayer->play();
        isPlaying = true;
        qDebug() << "Music played from lyrics interface";
    }

    // 更新按钮状态
    updatePlayPauseButton();
}
// 更新"播放/暂停"按钮状态处理函数
void Lyrics_interface::updatePlayPauseButton()
{
    if (isPlaying) {
        ui->pushButton->setIcon(QIcon(":/暂停"));
        ui->pushButton->setText("暂停");
    } else {
        ui->pushButton->setIcon(QIcon(":/继续"));
        ui->pushButton->setText("继续");
    }

    // 设置合适的尺寸
    ui->pushButton->setIconSize(QSize(20, 20));
    ui->pushButton->setMinimumSize(120, 35);
}
// 添加歌曲到歌单按钮点击处理
void Lyrics_interface::onAddToPlaylistClicked()
{
    if (!mediaPlayer) {
        QMessageBox::warning(this, "提示", "没有正在播放的歌曲！");
        return;
    }

    // 这里需要从主界面获取歌单列表
    // 由于lyrics_interface不直接访问主界面的歌单数据，我们发射信号让主界面处理
    // 主界面收到信号后应该调用这个对话框

    // 临时方案：直接显示对话框，歌单列表需要从外部设置
    showPlaylistSelectionDialog();
}

// 设置歌单列表（由主界面调用）
void Lyrics_interface::setPlaylistItems(const QStringList& playlists)
{
    // 如果对话框已经创建，更新列表
    if (playlistListWidget) {
        playlistListWidget->clear();
        playlistListWidget->addItems(playlists);
    }
}
// 显示事件 - 当界面显示时开始更新歌词
void Lyrics_interface::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    startLyricsUpdate();
    progressTimer->start();  // 修复拼写错误
    updateProgress(); // 立即更新一次
}

// 隐藏事件 - 当界面隐藏时停止更新歌词
void Lyrics_interface::hideEvent(QHideEvent *event)
{
    QWidget::hideEvent(event);
    stopLyricsUpdate();
    progressTimer->stop();  // 停止进度定时器
}

// 设置媒体播放器
void Lyrics_interface::setMediaPlayer(QMediaPlayer *player)
{
    mediaPlayer = player;

    if (mediaPlayer) {
        // 连接媒体播放器的信号
        connect(mediaPlayer, &QMediaPlayer::durationChanged, this, &Lyrics_interface::updateDuration);
        connect(mediaPlayer, &QMediaPlayer::positionChanged, this, &Lyrics_interface::updatePosition);

        // 初始化显示
        updateDuration(mediaPlayer->duration());
        updatePosition(mediaPlayer->position());
        // 更新初始播放状态
        isPlaying = (mediaPlayer->state() == QMediaPlayer::PlayingState);
        updatePlayPauseButton();
    }
}
// 开始歌词更新
void Lyrics_interface::startLyricsUpdate()
{
    lyricsTimer->start();
    updateLyricsDisplay(); // 立即更新一次
    qDebug() << "Lyrics update started";
}

// 停止歌词更新
void Lyrics_interface::stopLyricsUpdate()
{
    lyricsTimer->stop();
    qDebug() << "Lyrics update stopped";
}

// 加载歌词
void Lyrics_interface::loadLyrics(const QString& lyricsText)
{
    parseLyrics(lyricsText);
    updateLyricsDisplay();
}


//歌词解析函数
void Lyrics_interface::parseLyrics(const QString& lyricsText)
{
    lyrics.clear();

    if (lyricsText.isEmpty()) {
        lyrics.append({0, "暂无歌词"});
        return;
    }

    QStringList lines = lyricsText.split('\n');
    // 修复正则表达式 - 匹配 [mm:ss.xx] 格式
    QRegularExpression timeRegex("\\[(\\d+):(\\d+)\\.(\\d+)\\]");

    for (const QString& line : lines) {
        QRegularExpressionMatchIterator matchIterator = timeRegex.globalMatch(line);

        if (matchIterator.hasNext()) {
            QString lyricText = line;

            // 移除所有时间标签获取纯歌词文本
            while (matchIterator.hasNext()) {
                QRegularExpressionMatch match = matchIterator.next();
                lyricText.remove(match.captured(0));
            }
            lyricText = lyricText.trimmed();

            if (lyricText.isEmpty()) {
                continue;
            }

            // 重新匹配时间（因为上面的循环消耗了迭代器）
            matchIterator = timeRegex.globalMatch(line);
            while (matchIterator.hasNext()) {
                QRegularExpressionMatch match = matchIterator.next();

                int minutes = match.captured(1).toInt();
                int seconds = match.captured(2).toInt();
                int milliseconds = match.captured(3).toInt();

                // 处理不同精度的毫秒（2位或3位）
                if (match.captured(3).length() == 2) {
                    milliseconds *= 10; // 百分秒转毫秒
                }

                qint64 timeMs = minutes * 60000 + seconds * 1000 + milliseconds;

                if (!lyricText.isEmpty()) {
                    lyrics.append({timeMs, lyricText});
                }
            }
        }
        // 处理无时间标签的歌词行（如歌词信息）
        else if (!line.trimmed().isEmpty() && !line.trimmed().startsWith('[')) {
            lyrics.append({0, line.trimmed()});
        }
    }

    // 按时间排序
    std::sort(lyrics.begin(), lyrics.end(), [](const LyricLine& a, const LyricLine& b) {
        return a.time < b.time;
    });

    // 如果没有解析到有效歌词，添加默认提示
    if (lyrics.isEmpty()) {
        lyrics.append({0, "暂无歌词"});
    }

    qDebug() << "Parsed" << lyrics.size() << "lyric lines";
    for (const auto& line : lyrics) {
        qDebug() << "Time:" << line.time << "Text:" << line.text;
    }
}

// 查找当前歌词索引
int Lyrics_interface::findCurrentLyricIndex(qint64 position)
{
    if (lyrics.isEmpty()) return -1;

    // 使用二分查找提高效率
    int left = 0;
    int right = lyrics.size() - 1;
    int result = -1;

    while (left <= right) {
        int mid = left + (right - left) / 2;

        if (lyrics[mid].time <= position) {
            result = mid;
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return result;
}

// 格式化歌词显示
QString Lyrics_interface::formatLyricsDisplay(int currentIndex)
{
    if (currentIndex < 0 || lyrics.isEmpty()) {
        return "<p style='color: gray; font-size: 16px; text-align: center;'>暂无歌词</p>";
    }

    QString displayText;
    displayText += "<div style='text-align: center; line-height: 1.8;'>";

    // 显示前3句歌词
    for (int i = qMax(0, currentIndex - 3); i < currentIndex; ++i) {
        if (i < lyrics.size()) {
            displayText += QString("<p style='color: #888; font-size: 14px; margin: 8px 0;'>%1</p>")
                          .arg(lyrics[i].text.toHtmlEscaped());
        }
    }

    // 当前歌词高亮显示
    if (currentIndex < lyrics.size()) {
        displayText += QString("<p style='color: #e74c3c; font-size: 18px; font-weight: bold; "
                              "margin: 12px 0; background: rgba(231, 76, 60, 0.1); "
                              "padding: 8px; border-radius: 4px;'>%1</p>")
                      .arg(lyrics[currentIndex].text.toHtmlEscaped());
    }

    // 显示后3句歌词
    for (int i = currentIndex + 1; i <= qMin(lyrics.size() - 1, currentIndex + 3); ++i) {
        displayText += QString("<p style='color: #888; font-size: 14px; margin: 8px 0;'>%1</p>")
                      .arg(lyrics[i].text.toHtmlEscaped());
    }

    displayText += "</div>";
    return displayText;
}

// 更新歌词显示
void Lyrics_interface::updateLyricsDisplay()
{
    if (!mediaPlayer || lyrics.isEmpty()) {
        ui->textBrowser->setHtml("<p style='color: gray; font-size: 16px; text-align: center;'>暂无歌词</p>");
        emit currentLyricChanged("暂无歌词");  // 发射信号
        return;
    }

    qint64 position = mediaPlayer->position();
    int currentIndex = findCurrentLyricIndex(position);

    // 只有当歌词索引发生变化时才更新显示，减少不必要的刷新
    if (currentIndex != lastLyricIndex) {
        QString displayText = formatLyricsDisplay(currentIndex);
        ui->textBrowser->setHtml(displayText);
        lastLyricIndex = currentIndex;

        // 发射当前歌词改变信号
        if (currentIndex >= 0 && currentIndex < lyrics.size()) {
            emit currentLyricChanged(lyrics[currentIndex].text);
        } else {
            emit currentLyricChanged("暂无歌词");
        }

        // 自动滚动到当前歌词位置
        scrollToCurrentLyric(currentIndex);
    }
}

//滚动到当前歌词
void Lyrics_interface::scrollToCurrentLyric(int currentIndex)
{
    QTextCursor cursor = ui->textBrowser->textCursor();
    cursor.movePosition(QTextCursor::Start);

    // 计算需要跳过的行数（前3行）
    int linesToSkip = qMax(0, currentIndex - 3);
    for (int i = 0; i < linesToSkip && !cursor.atEnd(); ++i) {
        cursor.movePosition(QTextCursor::Down);
    }

    ui->textBrowser->setTextCursor(cursor);
    ui->textBrowser->ensureCursorVisible();
}
// 格式化时间显示 (毫秒 -> mm:ss)
QString Lyrics_interface::formatTime(qint64 milliseconds)
{
    qint64 seconds = milliseconds / 1000;
    qint64 minutes = seconds / 60;
    seconds = seconds % 60;

    return QString("%1:%2")
        .arg(minutes, 2, 10, QLatin1Char('0'))
        .arg(seconds, 2, 10, QLatin1Char('0'));
}

// 更新播放进度显示
void Lyrics_interface::updateProgress()
{
    if (!mediaPlayer || isSliderPressed) {
        return;
    }

    qint64 position = mediaPlayer->position();
    qint64 duration = mediaPlayer->duration();

    // 更新进度条
    if (duration > 0) {
        ui->horizontalSlider->setValue(static_cast<int>(position * 100 / duration));
    }

    // 更新时间标签
    ui->label->setText(formatTime(position));
    ui->label_2->setText(formatTime(duration));
}

// 进度条拖动事件
void Lyrics_interface::onSliderMoved(int position)
{
    if (!mediaPlayer) {
        return;
    }

    isSliderPressed = true;

    // 计算新的播放位置
    qint64 newPosition = static_cast<qint64>(mediaPlayer->duration() * position / 100);

    // 更新当前时间显示
    ui->label->setText(formatTime(newPosition));
}

// 进度条释放事件
void Lyrics_interface::onSliderReleased()
{
    if (!mediaPlayer) {
        return;
    }

    // 计算新的播放位置并设置
    qint64 newPosition = static_cast<qint64>(mediaPlayer->duration() * ui->horizontalSlider->value() / 100);
    mediaPlayer->setPosition(newPosition);

    isSliderPressed = false;
}

// 更新总时长
void Lyrics_interface::updateDuration(qint64 duration)
{
    ui->horizontalSlider->setRange(0, 100);
    ui->label_2->setText(formatTime(duration));
}

// 更新当前位置
void Lyrics_interface::updatePosition(qint64 position)
{
    if (!isSliderPressed) {
        ui->label->setText(formatTime(position));

        qint64 duration = mediaPlayer->duration();
        if (duration > 0) {
            ui->horizontalSlider->setValue(static_cast<int>(position * 100 / duration));
        }
    }
}
// 返回按钮点击处理
void Lyrics_interface::onBackButtonClicked()
{
    emit backToMain();  // 发射返回主界面的信号
}
// 设置按钮图标
void Lyrics_interface::setupButtonIcons()
{
    // 重新播放按钮图标
    ui->pushButton_2->setIcon(QIcon(":/重新播放"));
    ui->pushButton_2->setIconSize(QSize(20, 20));

    // 上一首按钮图标
    ui->pushButton_3->setIcon(QIcon(":/上一曲"));
    ui->pushButton_3->setIconSize(QSize(20, 20));

    // 下一首按钮图标
    ui->pushButton_4->setIcon(QIcon(":/下一曲"));
    ui->pushButton_4->setIconSize(QSize(20, 20));

    // 设置合适的按钮尺寸
    ui->pushButton_2->setMinimumSize(100, 35);
    ui->pushButton_3->setMinimumSize(100, 35);
    ui->pushButton_4->setMinimumSize(100, 35);
    ui->pushButton_5->setMinimumSize(40, 25);
    ui->pushButton_6->setMinimumSize(40, 25);
}

// 重新播放
void Lyrics_interface::onRestartButtonClicked()
{
    if (!mediaPlayer) {
        return;
    }

    mediaPlayer->setPosition(0);
    if (!isPlaying) {
        mediaPlayer->play();
        isPlaying = true;
        updatePlayPauseButton();
    }

    qDebug() << "Restart playback from beginning";
}

// 上一首
void Lyrics_interface::onPreviousButtonClicked()
{
    emit previousSongRequested();
    qDebug() << "Previous song requested";
}

// 下一首
void Lyrics_interface::onNextButtonClicked()
{
    emit nextSongRequested();
    qDebug() << "Next song requested";
}

// 音量增加5%
void Lyrics_interface::onVolumeAddButtonClicked()
{
    currentVolume = qMin(100, currentVolume + 5);
    ui->verticalSlider->setValue(currentVolume);
    updateVolume();
}

// 音量减少5%
void Lyrics_interface::onVolumeSubButtonClicked()
{
    currentVolume = qMax(0, currentVolume - 5);
    ui->verticalSlider->setValue(currentVolume);
    updateVolume();
}

// 音量滑块移动
void Lyrics_interface::onVolumeSliderMoved(int value)
{
    currentVolume = value;
    updateVolume();
}

// 更新音量显示和设置
void Lyrics_interface::updateVolume()
{
    if (mediaPlayer) {
        mediaPlayer->setVolume(currentVolume);
    }
    updateVolumeDisplay();
}

// 更新音量显示
void Lyrics_interface::updateVolumeDisplay()
{
    ui->label_3->setText(QString("%1%").arg(currentVolume));
}
